package org.example.springblog3.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.example.springblog3.constant.Constants;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {

    private static final long JWT_EXPIRATION = 60 * 60 * 1000;

    private static final String sectrStr = "2X3rGwxLnnD6sjRbvIUGnViuB530+EPsetj3hQ8iVwo=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(sectrStr));

    //生成token
    public static  String genJwtToken(Map<String, Object> claim){
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis()+JWT_EXPIRATION))
                .signWith(key)
                .compact();
        System.out.println(token);
        return token;
    }


    //校验token：
    //claims为null表示校验失败

    public static  Claims parseToken(String token){
        log.info("开始校验token：接收到的token：{}",token);
        JwtParser build  = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();
        }catch(Exception e){
            log.info("解析token失败：token：{}",token);
            return null;
        }
        return claims;
    }

    //从解析过后的JWT令牌中获取到ID：
    public static  Integer getIdByToken(String token){
        //解析token，获取到载荷信息：
        Claims claims  = parseToken(token);
        if(claims != null){
            Integer userId = (Integer) claims.get(Constants.TOKEN_ID);
            if(userId > 0){
                return userId;
            }
        }
        return null;
    }
}
